
// 文件类型和后缀的映射
const mediaMap = new Map([
    ['audio/mpeg', '.mp3'],
    ['audio/aac', '.aac'],
    ['audio/midi', '.mid'],
    ['audio/x-midi', '.midi'],
    ['audio/ogg', '.oga'],
    ['audio/wav', '.wav'],
    ['audio/webm', '.weba'],
    ['application/octet-stream', '.bin'],
    ['image/bmp', '.bmp'],
    ['image/jpeg', '.jpeg'],
    ['text/javascript', '.mjs'],
    ['text/plain', '.txt'],
]);

/**
 * 将返回值通过文件的形式下载下来
 * @param {后端的response}} response 
 */
function streamToBlob(response, fileName) {
    let contentType = response.headers['content-type'].split(';')[0];
    let suffix = mediaMap.get(contentType) || mediaMap.get('application/octet-stream');
    console.log('下载文件：',fileName + suffix);
    // 将二进制流转为blob
    const blob = new Blob([response.data], { type: contentType })
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
        window.navigator.msSaveBlob(blob, decodeURI(fileName)+ suffix)
    } else {
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(blob)
        // 创建a标签，用于跳转至下载链接
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', decodeURI(fileName)+ suffix)
        // 兼容：某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
        }
        // 挂载a标签
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL)
    }
}

export {
    streamToBlob
}